﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PropertyManagment.common.Filter;
using PropertyManagment.common.lang;
using PropertyManagment.config.cache;
using PropertyManagment.config.jwt;
using PropertyManagment.service;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace PropertyManagment.controllers {

    /// <summary>
    /// 异常信息控制器
    /// </summary>
    public class ErrorController : Controller{

        /// <summary>
        /// 注入ASP.NET Core ILogger服务。
        /// 将控制器类型指定为泛型参数。
        /// 这有助于我们进行确定哪个类或控制器产生了异常，然后记录它
        /// </summary>
        public ILogger<ErrorController> logger { get; set; }

        /// <summary>
        /// 异常状态码处理
        /// </summary>
        /// <param name="statusCode">状态码</param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        [Route("Error/{statusCode}")]
        public Result HttpStatusCodeHandler(int statusCode) {

            var statusCodeResult = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
            string msg = "访问失败";

            switch (statusCode) {
                case 401:
                    msg = "请先登录";
                    break;
                case 403:
                    msg = "没有权限访问";
                    break;
                case 404:
                    msg = "NotFound";
                    break;
                case 405:
                    msg = "Method Not Allowed";
                    break;
            }
            logger.LogError($"发生了一个404错误。路径={statusCodeResult.OriginalPath}以及查询字符串={statusCodeResult.OriginalQueryString}");
            return Result.fail(statusCode, msg, "");
        }

        /// <summary>
        /// 异常处理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        [Route("Error")]
        public Result Error() {
            var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

            logger.LogError($"路径:{exceptionHandlerPathFeature.Path},产生了一个错误{exceptionHandlerPathFeature.Error}");
            //ViewBag.ExceptionPath = exceptionHandlerPathFeature.Path;
            //ViewBag.ExceptionMessage = exceptionHandlerPathFeature.Error.Message;
            //ViewBag.StackTrace = exceptionHandlerPathFeature.Error.StackTrace;
            return Result.fail("Error");
        }
    }
}
